package at.sii.n4w;

import org.json.JSONArray;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.support.v4.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class TransportationFragment extends Fragment {
	private static final String ARG_NFCDATA = "nfcdata";
	public static final String TAG = "NFC4WLAN";
	public static Bundle args;
	public View rootView;
	public TextView textViewJSONResponse;
	public TextView textViewHaltestelle;

	// JSON url for A1
	private String f_stationID = "4643"; // U6 Direction FLORIDSDORF
	private String f_url;

	// JSON url for A2
	private String s_stationID = "4648"; // U6 Direction SIEBENHIRTEN
	private String s_url;

	// JSON Node names for A1
	private static String f_TAG_NAME = "name";
	private static String f_TAG_TITLE = "title";
	private static String f_TAG_COUNTDOWN = "countdown";
	private static String f_TAG_TOWARDS = "towards";
	private static String f_TAG_TIMEREAL = "timeReal";

	// JSON Node names for A2
	private static String s_TAG_NAME = "name";
	private static String s_TAG_TITLE = "title";
	private static String s_TAG_COUNTDOWN = "countdown";
	private static String s_TAG_TOWARDS = "towards";
	private static String s_TAG_TIMEREAL = "timeReal";

	// Lines JSONArray
	// A1
	JSONArray f_lines = null;
	JSONObject f_help = null;

	// A2
	JSONArray s_lines = null;
	JSONObject s_help = null;

	// Arraylist
	// A1
	HashMap<String, String> f_linesArray;
	// A2
	HashMap<String, String> s_linesArray;

	Bundle savedInstanceState;

	public TransportationFragment() {

	}

	public static Fragment newInstance() {
		TransportationFragment fragment = new TransportationFragment();
		args = new Bundle();

		args.putString(ARG_NFCDATA, "empty");
		fragment.setArguments(args);
		return fragment;
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		Log.d(TAG, "Taginhalt: " + getArguments().getString(ARG_NFCDATA));

		rootView = inflater.inflate(R.layout.fragment_transportation,
				container, false);
		textViewHaltestelle = (TextView) rootView
				.findViewById(R.id.tag_haltestelle);
		textViewHaltestelle.setText("Haltestellen #" + f_stationID + " #"
				+ s_stationID);

		textViewJSONResponse = (TextView) rootView
				.findViewById(R.id.tag_haltestelleDaten);

		textViewJSONResponse.setText("");

		Button btnTransportation = (Button) rootView
				.findViewById(R.id.transportation_button);
		btnTransportation.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d(TAG, "get haltestelle");

				setText();
				new GetLine().execute();
			}
		});

		f_linesArray = new HashMap<String, String>();
		s_linesArray = new HashMap<String, String>();

		return rootView;
	}

	public void setText() {
		if (getArguments().getString(ARG_NFCDATA).matches(".+@#@.+@#@.+@#@.+")) {
			f_stationID = getArguments().getString(ARG_NFCDATA).split("@#@")[2];
			s_stationID = getArguments().getString(ARG_NFCDATA).split("@#@")[3];

			textViewHaltestelle.setText("Haltestellen: #" + f_stationID
					+ " & #" + s_stationID);
			textViewJSONResponse.setText("");

		} else {
			textViewJSONResponse
					.setText("No stations on nfc tag found, using default.");
		}
	}

	public void refreshData(String result) {
		args.putString(ARG_NFCDATA, result);
		setText();
		Log.d(TAG, "read refreshData " + getArguments().getString(ARG_NFCDATA));
	}

	public void onResume() {
		super.onResume();
		setText();
		Log.d(TAG, "read onResume");
	}

	public void onPause() {
		super.onPause();
		Log.d(TAG, "read onPause");
	}

	private class GetLine extends AsyncTask<Void, Void, Void> {
		String textviewtext = "";

		private GetLine() {
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// Service handler instance
			ServiceHandler sh = new ServiceHandler();

			// request to url and getting response
			// A1
			f_url = "http://www.wienerlinien.at/ogd_realtime/monitor?rbl="
					+ f_stationID + "&sender=imXvaxZR5F"; // currently TEST-Key is
															// included
			String f_jsonString = sh.makeServiceCall(f_url, ServiceHandler.GET);
			// A2
			s_url = "http://www.wienerlinien.at/ogd_realtime/monitor?rbl="
					+ s_stationID + "&sender=imXvaxZR5F"; // currently TEST-Key is
															// included
			String s_jsonString = sh.makeServiceCall(s_url, ServiceHandler.GET);

			// Log.d("Response: ", "> " + f_jsonString);
			// Log.d("Response: ", "> " + s_jsonString);

			if (f_jsonString != null && s_jsonString != null) {
				try {
					JSONObject f_jsonObj = new JSONObject(f_jsonString);
					JSONObject s_jsonObj = new JSONObject(s_jsonString);

					// Get JSON Array Node for A1
					f_help = f_jsonObj.getJSONObject("data");
					f_lines = f_help.getJSONArray("monitors");

					// Get JSON Array Node for A2
					s_help = s_jsonObj.getJSONObject("data");
					s_lines = s_help.getJSONArray("monitors");

					String f_countdown = "\n";
					String f_timeReal = "\n";
					String s_countdown = "\n";
					String s_timeReal = "\n";
					// looping through A1
					for (int i = 0; i < f_lines.length(); i++) {
						JSONObject c = f_lines.getJSONObject(i);
						JSONArray d = c.getJSONArray("lines");
						JSONObject e = c.getJSONObject("locationStop");
						JSONObject o = e.getJSONObject("properties");
						String title = o.getString("title");
						f_linesArray.put(f_TAG_TITLE, title);
						for (int j = 0; j < d.length(); j++) {
							JSONObject f = d.getJSONObject(i);
							String name = f.getString("name");
							String towards = f.getString("towards");
							f_linesArray.put(f_TAG_NAME, name);
							f_linesArray.put(f_TAG_TOWARDS, towards);

							JSONObject g = f.getJSONObject("departures");
							JSONArray h = g.getJSONArray("departure");

							for (int k = 0; k < h.length(); k++) {
								JSONObject l = h.getJSONObject(k);

								JSONObject m = l.getJSONObject("departureTime");
								f_countdown += m.getString("countdown")
										+ " min.\n";
								f_timeReal += m.getString("timeReal")
										.substring(11, 16) + "\n";
								f_linesArray.put(f_TAG_COUNTDOWN, f_countdown);
								f_linesArray.put(f_TAG_TIMEREAL, f_timeReal);
							}
						}
					}

					// looping through A2
					for (int i = 0; i < s_lines.length(); i++) {
						JSONObject c = s_lines.getJSONObject(i);
						JSONArray d = c.getJSONArray("lines");
						JSONObject e = c.getJSONObject("locationStop");
						JSONObject o = e.getJSONObject("properties");
						String title = o.getString("title");
						s_linesArray.put(s_TAG_TITLE, title);
						for (int j = 0; j < d.length(); j++) {
							JSONObject f = d.getJSONObject(i);
							String name = f.getString("name");
							String towards = f.getString("towards");
							s_linesArray.put(s_TAG_NAME, name);
							s_linesArray.put(s_TAG_TOWARDS, towards);

							JSONObject g = f.getJSONObject("departures");
							JSONArray h = g.getJSONArray("departure");

							for (int k = 0; k < h.length(); k++) {
								JSONObject l = h.getJSONObject(k);
								JSONObject m = l.getJSONObject("departureTime");
								s_countdown += m.getString("countdown")
										+ " min.\n";
								s_timeReal += m.getString("timeReal")
										.substring(11, 16) + "\n";
								s_linesArray.put(s_TAG_COUNTDOWN, s_countdown);
								s_linesArray.put(s_TAG_TIMEREAL, s_timeReal);
							}
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			/* updating parsed json data into textview */

			textviewtext = "Current station: " + f_linesArray.get(f_TAG_NAME)
					+ " " + f_linesArray.get(f_TAG_TITLE) + "\n"
					+ "Direction: " + f_linesArray.get(f_TAG_TOWARDS)
					+ "\nNext trains: " + f_linesArray.get(f_TAG_COUNTDOWN)
					+ "Departure:" + f_linesArray.get(f_TAG_TIMEREAL) + ""
					+ "\n\n" + "Current station: "
					+ f_linesArray.get(f_TAG_NAME) + " "
					+ f_linesArray.get(f_TAG_TITLE) + "\n" + "Direction: "
					+ s_linesArray.get(s_TAG_TOWARDS) + "\nNext trains: "
					+ s_linesArray.get(s_TAG_COUNTDOWN) + "Departure:"
					+ s_linesArray.get(s_TAG_TIMEREAL) + "";

			// Log.d(TAG, textviewtext);

			textViewJSONResponse.setText(textviewtext);
		}

	}
}